<template>

  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :width="width"
    :visible="visible"
    @close="handleCancel"
    destroyOnClose
  >
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="套餐名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageName">
              <a-input v-model="model.packageName" placeholder="请输入套餐名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="套餐备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageRemark">
              <a-textarea
                v-model="model.packageRemark"
                placeholder="请输入备注"
                :auto-size="{ minRows: 3, maxRows: 5 }"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>

    <div>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-button class="editable-add-btn" @click="addProduct" style="margin-bottom: 10px;width: 100%">
            选择产品
          </a-button>
        </a-col>
        <a-col :span="12">
          <a-button type="primary" @click="handleOk" style="width: 100%;">保存</a-button>
        </a-col>
      </a-row>

      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoadList"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i">
            <div>
              <div class="name">{{item.productName || ''}}</div>
              <div class="contact">
                <span>产品售价：{{ item.productPrice || '无' }}</span>
                <span style="float: right">
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(item)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
              </div>
              <div class="contact">
                <span>单位：{{ item.unit || '无'}}</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap">

        <span slot="action" slot-scope="text, record">
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>-->

    </div>
    <select-product-modal ref="selectProductModal" @selectOk="selectOk"></select-product-modal>
  </a-drawer>

  <!--<j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk"
    cancelText="关闭">


  </j-modal>-->
</template>

<script>

  import {mixinDevice} from '@/utils/mixin'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction,httpAction,deleteAction} from "@/api/manage";
  import selectProductModal from './selectProductModal'

  export default {
    name: 'productPackageModal',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      selectProductModal,
    },
    data() {
      return {
        loading: false,
        dataSource: [],
        cacheData: [],
        disableSubmit: false,
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'产品名称',
            align:"center",
            dataIndex: 'productName',
          },
          /*{
            title:'产品类型',
            align:"center",
            dataIndex: 'productManage.productTypeName',
          },*/
          {
            title:'产品售价',
            align:"center",
            dataIndex: 'productPrice'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        title: '',
        width: '100%',
        visible: false,
        fullscreen: true,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        validatorRules: {
          packageName: [{ required: true, message: '套餐名称不能为空' }],
          packageRemark: [
            { max: 100, message: '最多输入100个字符' },
          ],
        },
        confirmLoading: false,
        selectedRowKeys: [],
        selectedRows: [],
        addRowBeginIndex: 0,
        url: {
          list: "/ghProductPackageItem/list",
          add: "/ghProductPackage/add",
          edit: "/ghProductPackage/edit",
          delete: "/ghProductPackageItem/delete"
        },
        finished: false,
      }
    },
    created() {

    },
    methods:{
      //下一页
      onLoadList(){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadProductPackageItemData(arg){
        if (arg === 1){
          this.ipagination.current = 1;
          this.dataSource = [];
          this.finished = false;
        }
        this.loading = true;
        let params = {
          productPackageId: this.model.id
        }
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = [...this.dataSource, ...res.result.records]
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      handleOk(){
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.dataSource.length === 0){
              this.$message.warning("请至少选择一条数据")
              return;
            }
            let httpUrl = "";
            let method = "";
            if (!this.model.id){
              httpUrl += this.url.add
              method = "post"
            }else {
              httpUrl += this.url.edit
              method = "put"
            }
            this.model.ghProductManageList = this.dataSource;
            httpAction(httpUrl,this.model,method).then((res)=>{
              if (res.success){
                this.$message.success(res.message)
                this.$emit('modalOk')
              }else {
                this.$message.warning(res.message)
              }
            }).finally(()=>{
              this.close()
            })
          }
        })
      },
      close(){
        this.dataSource = []
        this.model = {};
        this.visible = false;
      },
      handleCancel(){
        this.close()
      },
      add(){
        this.dataSource = []
        this.title = "新增产品套餐";
        this.visible = true;
      },
      edit(record){
        this.model = Object.assign({},record);
        this.title = "编辑产品套餐";
        this.loadProductPackageItemData(1);
        this.visible = true;
      },
      addProduct(){
        this.$refs.selectProductModal.title = "选择产品"
        this.$refs.selectProductModal.visible = true;
        this.$refs.selectProductModal.initTreeData()
      },
      selectOk(productArr){
        let productArr1 = productArr
        let obj = ""
        for (let i=0;i<productArr1.length;i++){
          obj = this.dataSource.find(item=>{
            return item.id == productArr1[i].id
          })
          if (!obj && obj!=""){
           this.dataSource.push(productArr1[i])
          }
        }
      },
      handleDelete(record){
        if (this.model.id && record.packageItemId){
          let that = this;
          deleteAction(that.url.delete, {id: record.packageItemId}).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              //that.loadProductPackageItemData();
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            this.loading = false
          });
        }
        const data = [...this.dataSource]
        this.dataSource = data.filter(item => item.id !== record.id)
      },
    }
  }
</script>

<style scoped lang="less">
  @import '~@assets/less/common.less';
  .select-pk{
    display:flex;
    align-items:center;
    margin:10px 0;
    &>span{
      font-weight: bold;
    }
    &-text{
      width: calc(100% - 6em);
      height: 30px;
      text-indent: 1em;
      line-height: 28px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
    }
  }
  .list{
    overflow-y: scroll;
    height:calc(100vh - 420px);
    margin-top: 10px;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list{
    /*display: flex;*/
    align-items: center;
    border-top: 1px solid #d9d9d9;
    .name{
      font-size: 13px;
      color: #161616;
      line-height: normal;
      margin-top: 5px;
    }
    .contact{
      margin-top: 5px;
      font-size: 12px;
      color: #a39f9f;
      margin-bottom: 5px;
    }
  }
</style>